// 优先加载初始化文件
import './init'
import 'reflect-metadata'
import express from 'express'
import bodyParser from 'body-parser'
import NotFoundError from '@/errors/NotFoundError'
import timeOutMiddleware from '@/middlewares/timeout'
import databaseMiddleware from '@/middlewares/database'
import { requestMiddleware, errorRequestMiddleware } from '@/middlewares/http-request'
import apiRouter from '@/routes'
import { consoleLogger, errorLogger } from '@/utils/logger'
import { destroyDatabaseConnections } from '@/utils/database'
import { appInit } from './utils'

// 端口
const port = process.env.PORT || 3000

// 初始化启动函数，进入后立即执行
export default () => {
  // 创建 express 应用
  const app = express()
  //注入前置中间件

  // 用 body-parser 中间件 解析请求体
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({ extended: true }))
  // 数据库连接状态检查中间件
  app.use(databaseMiddleware)
  // 注册timeOutMiddleware中间件
  app.use(timeOutMiddleware)
  // 请求中间件，绑定请求对象到容器，记录请求日志
  app.use(requestMiddleware)

  // 注册home路由
  app.use('/api', apiRouter)

  // 未注册的路由错误处理中间件 返回404异常
  app.use((_req, _res) => {
    throw new NotFoundError()
  })

  // 捕获异常日志处理中间件
  app.use(errorRequestMiddleware)

  const server = app.listen(port, appInit)

  // 优雅关闭函数
  const gracefulShutdown = async () => {
    consoleLogger.warn('接收到退出信号.')
    await destroyDatabaseConnections()
    server.close(() => {
      consoleLogger.warn('Express进程已关闭，服务不可用啦.')
      process.exit(0)
    })
  }
  // 全局异常处理
  process
    .on('SIGINT', gracefulShutdown)
    .on('SIGTERM', gracefulShutdown)
    .on('uncaughtException', err => errorLogger.error('Uncaught Exception:', err)) // 记录未捕获的异常
    .on('unhandledRejection', (reason, promise) =>
      errorLogger.error('Unhandled Rejection at:', promise, 'reason:', reason)
    ) // 记录未处理的 Promise 拒绝

  return app
}
